//import AMapWX from '@/utils/amap-wx.130'
// new AMapWX({ key: 'ff1d3581dbd2449da8afa68b9078d3ee' })
const myAmapFun = {}
export const useAddressStore = defineStore('address', () => {
  //当前是否授权定位
  let empowerPosition = $ref(false)
  const updateEmpower = (payload) => {
    empowerPosition = payload
  }
  //当前提货是自提还是外送
  let selfPickup: any = $ref(0) //自提 外送
  const updateSelfPickup = (payload) => {
    selfPickup = payload
  }
  //地址定位信息
  let locationInfo = $ref({
    latitude: '', //纬度
    longitude: '', //经度
    adcode: '', //城市code编码
    province: '', //城市省份
    city: '', //城市市
    district: '', //区
    detailAddress: '', //详细地址
  })
  //当前选择的地址
  let selectData: any = $ref({})
  const updateSelectData = (payload) => {
    selectData = payload
  }
  //当前地址的信息
  let currentLocation: any = $ref({})
  const updateCurrent = (payload) => {
    currentLocation = payload
  }
  //门店数据
  let storeList = $ref([])
  const updateStoreList = (payload) => {
    storeList = payload
  }
  //当前选择的门店
  let selectStores: any = $ref({})
  const updateSelectStores = async (payload) => {
    selectStores = payload
  }
  const time_to_sec = (time) => {
    if (time !== null) {
      let s: any = ''
      let hour = time.split(':')[0]
      let min = time.split(':')[1]
      let sec = time.split(':')[2]
      s = Number(hour * 3600) + Number(min * 60) + Number(sec)
      return s
    }
  }
  //获取店铺列表
  const getstoreList = async (pageNo, pageSize) => {
    const url = currentLocation.longitude ? '/qqyapi/product/store/list' : '/qqyapi/product/product/getDefaultTeaStore'
    const method = currentLocation.longitude ? 'post' : 'get'
    const formData = currentLocation.longitude ? { latitude: currentLocation.latitude, longitude: currentLocation.longitude } : {}
    const { data, error, status } = await Fetch(url, {
      method,
      headers: {
        AppType: 2,
      },
      data: {
        ...formData,
        pageNum: pageNo,
        pageSize,
      },
    })
    if (status === 200 && data.code === 0) {
      let tempList: any = currentLocation.longitude ? data.result?.list : [data.result]
      tempList.forEach((item) => {
        let tempTime: any = new Date()
        let dateHours = tempTime.getHours() //获取小时
        let dateMinutes = tempTime.getMinutes() //获取分钟
        let dateSeconds = tempTime.getSeconds() //获取秒
        tempTime = `${dateHours}:${dateMinutes}:${dateSeconds}`
        tempTime = time_to_sec(tempTime)
        let starTime: any = time_to_sec(item.storeStartTime)
        let endTime: any = time_to_sec(item.storeEndTime)
        if (Number(tempTime) < Number(endTime) && Number(tempTime) > Number(starTime)) {
          item.isOpen = true
        } else {
          item.isOpen = false
        }
      })
      updateStoreList(tempList)
    }
    return data.result?.totalPage || 0
  }
  //获取最近的门店
  const getRecentlyStore = async (latitude, longitude) => {
    const url = latitude && longitude ? '/qqyapi/product/store/getStoreByLocation' : '/qqyapi/product/product/getDefaultTeaStore'
    const method = latitude && longitude ? 'post' : 'get'
    const formData = latitude && longitude ? { latitude, longitude } : {}
    const { data, error, status } = await Fetch(url, {
      method,
      headers: {
        AppType: 2,
      },
      data: formData,
    })
    if (status === 200 && data.code === 0) {
      updateSelectStores(data.result)
    }
  }
  //修改定位信息
  const updateLocation = (payload) => {
    locationInfo = { ...locationInfo, ...payload }
  }

  //监听经纬度发送变化重新请求地理位置
  watch(() => locationInfo.latitude, (newVal, oldVal) => {
    if (locationInfo?.latitude) {
      if (newVal === oldVal) {
        return
      }
      getPosition({ location: `${locationInfo.longitude},${locationInfo.latitude}` })
    }
  })
  const isEmpty = (obj) => {
    return JSON.stringify(obj) === '{}'
  }
  //获取地理位置信息
  const getPosition = (obj) => {
    myAmapFun.getRegeo({
      ...obj,
      success(data) {
        const { regeocodeData, latitude, longitude } = data[0]
        const { adcode, province, city, district } = regeocodeData?.addressComponent
        if (isEmpty(obj)) updateCurrent(data[0])
        updateLocation({ latitude, longitude, adcode, province, city, district })
        getRecentlyStore(latitude, longitude)
      },
      fail: () => {
        updateLocation({})
        empowerPosition = false
      },
    })
  }
  //获取周边的POI
  const getPOI = () => {
    let dataList = {}
    myAmapFun.getPoiAround({
      success(data) {
        dataList = data
      },
    })
    return dataList
  }
  //管理地址信息
  let listData: any[] = $ref([])
  let listtotalPage = $ref(0)
  //修改管理地址信息
  const updateListData = (payload) => {
    listData = payload
  }
  const updatetotalPage = (payload) => {
    listtotalPage = payload
  }
  //获取地址列表
  const getListData = async (userId, pageNo, pageSize) => {
    const { data, error, status } = await Fetch('/qqyapi/mall-member/user/address/list', {
      method: 'post',
      headers: {
        userId,
      },
      data: {
        pageNo,
        pageSize,
      },
    })
    if (status === 200 && data.code === 0) {
      if (pageNo !== 1) {
        updateListData([...listData, ...data.result.list])
      } else {
        updateListData(data.result.list)
      }
      updatetotalPage(data.result.totalPage)
    }
    return data.result.totalPage
  }
  //删除地址列表
  const delListData = async (userId, itemId) => {
    const { data, error, status } = await Fetch(`/qqyapi/mall-member/user/address/delById/${itemId}`, {
      method: 'post',
      headers: {
        userId,
      },
    })
    if (status === 200 && data.code === 0) {
      getListData(userId, 1, 10)
      uni.showToast({
        title: '删除成功',
      })
    }
  }
  //保存修改地址列表 1:代表修改，0：代码添加保存
  const edit_save = async (type, userId, obj) => {
    let res = null
    const reqdata = {
      method: 'post',
      headers: {
        userId,
      },
      data: {
        ...obj,
        lat: locationInfo.latitude,
        lon: locationInfo.longitude,
        addressId: locationInfo.adcode,
      },
    }
    if (type === '1') {
      res = await Fetch('/qqyapi/mall-member/user/address/update', reqdata) as any
    } else {
      res = await Fetch('/qqyapi/mall-member/user/address/save', reqdata) as any
    }
    const { data, error, status } = res as any
    if (status === 200 && data.code === 0) {
      getListData(userId, 1, 10)
      clearIocationInfo()
      uni.showToast({
        title: type === '1' ? '修改成功' : '保存成功',
      })
    }
  }
  //获取默认的地址
  const defaultaddress = async (userId) => {
    const { data, error, status } = await Fetch('/qqyapi/mall-member/user/address/get/default', {
      method: 'get',
      headers: {
        userId,
      },
    })
    if (status === 200 && data.code === 0) {
      updateSelectData(data?.result ?? listData.length > 0 ? listData[0] : {})
      if (data.result !== null) {
        getRecentlyStore(data.result.lat, data.result.lon)
        uni.$emit('handleUpdateMethod')
      }
    }
  }
  const clearIocationInfo = () => {
    locationInfo = {} as any
  }

  // 点击自提切换购物车方式
  const changeDeliveryMethodSelfpickUp = async (UserId) => {
    const reqData = {
      method: 'post',
      data: {
        'deliveryMethod': 2,
        'trolleyType': 2,
      },
      headers: { UserId },
    }
    const { status, data, error } = await Fetch('/qqyapi/order/trolley/setTrolleyDeliveryMethod', reqData)
  }
  // 点击外送切换购物车方式
  const changeDeliveryMethodOutward = async (UserId) => {
    const reqData = {
      method: 'post',
      data: {
        'deliveryMethod': 1,
        'trolleyType': 2,
        'userAddressId': selectData.id,
      },
      headers: { UserId },
    }
    const { status, data, error } = await Fetch('/qqyapi/order/trolley/setTrolleyDeliveryMethod', reqData)
  }
  return {
    locationInfo: $$(locationInfo),
    currentLocation: $$(currentLocation),
    listData: $$(listData),
    listtotalPage: $$(listtotalPage),
    selectData: $$(selectData),
    selectStores: $$(selectStores),
    selfPickup: $$(selfPickup),
    storeList: $$(storeList),
    empowerPosition: $$(empowerPosition),
    getstoreList,
    getPosition,
    updateLocation,
    getPOI,
    getListData,
    delListData,
    defaultaddress,
    updateSelectData,
    clearIocationInfo,
    edit_save,
    getRecentlyStore,
    updateSelectStores,
    updateSelfPickup,
    changeDeliveryMethodSelfpickUp,
    changeDeliveryMethodOutward,
    updateEmpower,
  }
}, { unistorage: { key: 'config-address' } })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useAddressStore, import.meta.hot))
